package com.zhongshengnetwork.rightbe.login;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.MD5;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.BDCodeModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.ShareActivity;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class BDThirdActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private TopBarView topbar;
    private TextView tip_text;
    private EditText accountText;
    private EditText codeText;
    private Button codeBt;
    private EditText passwordText;
    private boolean isHasUser = false;

    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private Handler mHandler = null;
    private final static int TimeOut = 91;
    private int timeCount = 0;
    private static int delay = 1000;  //1s
    private static int period = 1000;  //1s

    private String passport = null;
    private String id;
    private int type;
    private String nickname;
    private String userHeader;
    private AVLoadingIndicatorView avi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        passport = getIntent().getStringExtra("passport");
        id = getIntent().getStringExtra(APIKey.idKey);
        type = getIntent().getIntExtra(APIKey.typeKey,0);
        nickname = getIntent().getStringExtra(APIKey.nicknameKey);
        userHeader = getIntent().getStringExtra(APIKey.headerKey);
        boolean noshow = getIntent().getBooleanExtra("noshow", false);
        setContentView(R.layout.activity_bdthird);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);
        tip_text = (TextView) findViewById(R.id.tip_text);
        tip_text.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());

        topbar.getRightTextView().setVisibility(View.VISIBLE);
        topbar.getRightTextView().setText("完成");
        topbar.getRightTextView().setTextSize(16);
        topbar.getRightTextView().setTextColor(getResources().getColor(R.color.mainColor));
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                bdThird();
            }
        });

        accountText = (EditText) findViewById(R.id.bd_account);
        codeText = (EditText) findViewById(R.id.bd_codetext);
        codeBt = (Button) findViewById(R.id.bd_codebt);
        passwordText = (EditText) findViewById(R.id.bd_password);
        passwordText.setVisibility(View.VISIBLE);

        LinearLayout activity_bdthird = (LinearLayout) findViewById(R.id.activity_bdthird);
        activity_bdthird.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

        accountText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        accountText.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        accountText.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        codeText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        codeText.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        codeText.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        passwordText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        passwordText.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        passwordText.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        codeBt.setBackgroundResource(AppThemeUtils.getInstance().getComsytleBg());

        codeBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                getCode();
            }
        });

        if (CommonUtils.isEmpty(passport)){
            //绑定手机号不变
            if (noshow == false){
                CustomDialog dialog = null;
                final CustomDialog.Builder builder = new CustomDialog.Builder(BDThirdActivity.this);
                builder.setTitle("温馨提示");
                builder.setMessage("根据相关政策，发布内容需要绑定手机号。");
                builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.show();
            }

        }else {
            //更换手机号
            topbar.getTitleView().setText("更换新手机号");
            passwordText.setVisibility(View.GONE);
            tip_text.setText("输入新手机号，获取并输入验证码后点击完成。");
        }

        // 定义Handler
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg == null){
                    return;
                }
                //handler处理消息
                if(msg.what>0){
                    codeBt.setText(msg.what+"秒");
                }else{
                    //在handler里可以更改UI组件
                    stopTimer();
                    codeBt.setText("获取验证码");
                }
            }
        };



    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        hintKeyBoard();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void startTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
        }

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (timeCount > 0){
                        timeCount--;
                    }
                    sendMessage(timeCount);
                }
            };
        }

        if(mTimer != null && mTimerTask != null ){
            if (timeCount == 0){
                timeCount = TimeOut;
                mTimer.schedule(mTimerTask, delay, period);
            }
        }

    }

    private void stopTimer(){
        if (mTimer != null) {
            timeCount = 0;
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        codeBt.setClickable(true);
        timeCount = 0;
    }

    public void sendMessage(int id){
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    //获取验证码
    private void getCode(){
        if (accountText.getText().toString().trim().length() < 11){
            ToastUtil.show(BDThirdActivity.this,"请输入11位手机号");
            return;
        }
        if (timeCount > 0){
            return;
        }

        if (CommonUtils.isEmpty(passport)){//绑定手机
            final Map<String,String> map = new HashMap<String, String>();
            map.put(APIKey.accountKey, accountText.getText().toString());
            map.put(APIKey.typeKey, "3");

            HttpsUtils.getthirdcodeDo(map, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        BDCodeModel bdCodeModel = GsonTools.getBDCodeModel(data);

                        if (bdCodeModel.getFlag().equals("1")){
                            isHasUser = true;
                            passwordText.setVisibility(View.INVISIBLE);
                        }else {
                            isHasUser = false;
                            passwordText.setVisibility(View.VISIBLE);
                        }

                        startTimer();
                    }else {
                        ToastUtil.show(BDThirdActivity.this,commonModel.getMsg());
                        stopTimer();
                        codeBt.setText("获取验证码");
                        codeBt.setClickable(true);
                        return;
                    }
                }

                @Override
                public void onError(String msg) {
                    stopTimer();
                    codeBt.setText("获取验证码");
                    codeBt.setClickable(true);
                }
            });
        }else {//更换手机
            final Map<String,String> map = new HashMap<String, String>();
            map.put(APIKey.accountKey, accountText.getText().toString());
            map.put("passport", passport);
            map.put(APIKey.typeKey, "5");
            map.put("token", CustomApplication.loginModel.getToken());
            HttpsUtils.getCodeDo(map, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        startTimer();
                    }else {
                        ToastUtil.show(BDThirdActivity.this,commonModel.getMsg());
                        stopTimer();
                        codeBt.setText("获取验证码");
                        codeBt.setClickable(true);
                        return;
                    }
                }

                @Override
                public void onError(String msg) {
                    stopTimer();
                    codeBt.setText("获取验证码");
                    codeBt.setClickable(true);
                }
            });
        }

    }

    //绑定第三方账号
    private void bdThird(){
        //检查数据是否完整
        if (accountText.getText().toString().trim().length() < 11){
            ToastUtil.show(BDThirdActivity.this,"请输入11位手机号");
            return;
        }
        if (codeText.getText().toString().trim().length() < 6){
            ToastUtil.show(BDThirdActivity.this,"请输入6位验证码");
            return;
        }


        if (CommonUtils.isEmpty(passport)){//绑定手机号
            if (isHasUser == false){
                if (passwordText.getText().toString().trim().length() < 6){
                    ToastUtil.show(BDThirdActivity.this,"请输入6~20位数字或字母密码");
                    return;
                }
            }

            avi.show();
            final Map<String,String> map = new HashMap<String, String>();
            map.put(APIKey.typeKey,"0");
            map.put(APIKey.codeKey,codeText.getText().toString());
            map.put(APIKey.accountKey,accountText.getText().toString());
            map.put(APIKey.passwordKey, MD5.GetMD5Code(passwordText.getText().toString()));
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            HttpsUtils.bindaccountDo(map, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    avi.hide();
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        ToastUtil.show(BDThirdActivity.this,"绑定成功");
                        CustomApplication.loginModel.setMobile(accountText.getText().toString());
                        Intent intent = new Intent();
                        intent.putExtra("mobile", accountText.getText().toString());
                        setResult(RESULT_OK, intent);//设置resultCode
                        finish();
                    }else {
                        ToastUtil.show(BDThirdActivity.this, commonModel.getMsg());
                    }
                }

                @Override
                public void onError(String msg) {
                    avi.hide();
                    ToastUtil.show(BDThirdActivity.this,"绑定失败");
                }
            });

        }else {//更换手机号
            avi.show();
            final Map<String,String> map = new HashMap<String, String>();
            map.put("randcode",codeText.getText().toString());
            map.put(APIKey.accountKey,accountText.getText().toString());
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            HttpsUtils.changeaccountDo(map, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    avi.hide();
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        ToastUtil.show(BDThirdActivity.this,"更换成功");
                        CustomApplication.loginModel.setMobile(accountText.getText().toString());
                        Intent intent = new Intent();
                        intent.putExtra("mobile", accountText.getText().toString());
                        setResult(RESULT_OK, intent);//设置resultCode
                        finish();
                    }else {
                        ToastUtil.show(BDThirdActivity.this, commonModel.getMsg());
                    }
                }

                @Override
                public void onError(String msg) {
                    avi.hide();
                    ToastUtil.show(BDThirdActivity.this,"绑定失败");
                }
            });
        }
    }

}
